// 封装倒计时逻辑函数
import { computed, onUnmounted, ref } from 'vue'
import dayjs from 'dayjs'

export const useCountDown = () => {
  // 1.响应式的数据
  let time = ref<number>(0)
  let timer: any = null
  // 格式化时间
  let formatTime = computed(() => dayjs.unix(time.value).format('mm分ss秒'))
  // 2.开启倒计时的函数
  const start = (currentTime: number) => {
    // 当前时间赋值给响应式时间formatTime
    time.value = currentTime
    // 开始倒计时的逻辑
    timer = setInterval(() => {
      time.value--
    }, 1000)
  }
  // 组件销毁时清除定时器，防止内存溢出
  onUnmounted(() => {
    // 如果timer存在则销毁
    timer && clearInterval(timer)
  })
  return {
    formatTime,
    start,
  }
}
